import React, { useState, useEffect, useCallback, useRef } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPaperPlane, faUpload, faTrash, faRefresh, faSpinner } from '@fortawesome/free-solid-svg-icons';
import APIClient from '../api/client';

// 创建API客户端实例
const apiClient = new APIClient();

const ChatWindow = ({ sessionId, onSessionDeleted }) => {
    // 消息列表状态
    const [messages, setMessages] = useState([]);
    // 输入框内容
    const [inputValue, setInputValue] = useState('');
    // 加载状态
    const [isLoading, setIsLoading] = useState(false);
    // 错误信息
    const [error, setError] = useState('');
    // 会话信息
    const [sessionInfo, setSessionInfo] = useState(null);
    // 文件上传状态
    const [uploading, setUploading] = useState(false);
    // 文件上传进度
    const [uploadProgress, setUploadProgress] = useState(0);
    // 聊天容器引用，用于滚动
    const chatContainerRef = useRef(null);
    // 输入框引用
    const inputRef = useRef(null);
    // 发送消息的控制器
    const abortControllerRef = useRef(null);

    // 初始化会话
    useEffect(() => {
        // 设置会话ID
        if (sessionId) {
            apiClient.setSessionId(sessionId);
            fetchSessionInfo();
        }

        // 添加键盘事件监听
        const handleKeyDown = (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSendMessage();
            }
        };

        document.addEventListener('keydown', handleKeyDown);

        return () => {
            document.removeEventListener('keydown', handleKeyDown);
            // 取消所有未完成的请求
            apiClient.cancelAllRequests();
        };
    }, [sessionId]);

    // 自动滚动到底部
    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    // 获取会话信息
    const fetchSessionInfo = useCallback(async () => {
        try {
            const data = await apiClient.getSessionInfo();
            setSessionInfo(data.session_info);
        } catch (error) {
            console.error('获取会话信息失败:', error);
            setError(error.message);
        }
    }, []);

    // 滚动到底部
    const scrollToBottom = useCallback(() => {
        if (chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
        }
    }, []);

    // 处理发送消息
    const handleSendMessage = useCallback(async () => {
        const message = inputValue.trim();
        if (!message || isLoading) return;

        // 添加用户消息到列表
        setMessages(prevMessages => [...prevMessages, {
            id: `user-${Date.now()}`,
            content: message,
            role: 'user',
            timestamp: new Date().toISOString()
        }]);

        // 清空输入框
        setInputValue('');
        // 设置加载状态
        setIsLoading(true);
        // 清除之前的错误
        setError('');

        // 创建新的消息对象
        let assistantMessage = {
            id: `assistant-${Date.now()}`,
            content: '',
            role: 'assistant',
            timestamp: new Date().toISOString(),
            isStreaming: true
        };

        // 添加助手消息到列表
        setMessages(prevMessages => [...prevMessages, assistantMessage]);

        try {
            // 发送消息并处理流式响应
            await apiClient.sendMessage(message, (data) => {
                if (data.status === 'stream') {
                    // 更新助手消息内容
                    setMessages(prevMessages => {
                        const index = prevMessages.findIndex(msg => 
                            msg.id === assistantMessage.id && msg.isStreaming
                        );
                        
                        if (index !== -1) {
                            const updatedMessages = [...prevMessages];
                            updatedMessages[index] = {
                                ...updatedMessages[index],
                                content: updatedMessages[index].content + data.content
                            };
                            return updatedMessages;
                        }
                        return prevMessages;
                    });
                } else if (data.status === 'end') {
                    // 结束流式响应
                    setMessages(prevMessages => {
                        const index = prevMessages.findIndex(msg => 
                            msg.id === assistantMessage.id && msg.isStreaming
                        );
                        
                        if (index !== -1) {
                            const updatedMessages = [...prevMessages];
                            updatedMessages[index] = {
                                ...updatedMessages[index],
                                isStreaming: false
                            };
                            return updatedMessages;
                        }
                        return prevMessages;
                    });
                    setIsLoading(false);
                } else if (data.status === 'error') {
                    // 处理错误
                    setError(data.content);
                    setIsLoading(false);
                }
            });
        } catch (error) {
            console.error('发送消息失败:', error);
            setError(error.message || '发送消息时发生错误');
            setIsLoading(false);
        }
    }, [inputValue, isLoading]);

    // 处理文件上传
    const handleFileUpload = useCallback(async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        setUploading(true);
        setUploadProgress(0);
        setError('');

        try {
            // 模拟上传进度
            const interval = setInterval(() => {
                setUploadProgress(prev => Math.min(prev + 10, 90));
            }, 200);

            // 上传文件
            const result = await apiClient.uploadDocument(file);

            // 清除进度条
            clearInterval(interval);
            setUploadProgress(100);

            // 添加系统消息
            setMessages(prevMessages => [...prevMessages, {
                id: `system-${Date.now()}`,
                content: `📎 文件 "${file.name}" 已上传成功。${result.document_count > 0 ? 
                    `已处理 ${result.document_count} 个文档片段。` : 
                    '但未提取到可处理的内容。'}`,
                role: 'system',
                timestamp: new Date().toISOString()
            }]);

            // 更新会话信息
            fetchSessionInfo();
        } catch (error) {
            console.error('上传文件失败:', error);
            setError(error.message || '上传文件时发生错误');
        } finally {
            setUploading(false);
            setUploadProgress(0);
            // 重置文件输入
            e.target.value = '';
        }
    }, [fetchSessionInfo]);

    // 处理清除历史
    const handleClearHistory = useCallback(async () => {
        if (!sessionId) return;

        if (window.confirm('确定要清除所有聊天历史记录吗？')) {
            try {
                await apiClient.clearHistory();
                setMessages([]);
                setError('');
                
                // 添加系统消息
                setMessages(prevMessages => [...prevMessages, {
                    id: `system-${Date.now()}`,
                    content: '📋 聊天历史已清除。',
                    role: 'system',
                    timestamp: new Date().toISOString()
                }]);
            } catch (error) {
                console.error('清除历史失败:', error);
                setError(error.message || '清除历史时发生错误');
            }
        }
    }, [sessionId]);

    // 处理删除会话
    const handleDeleteSession = useCallback(async () => {
        if (!sessionId) return;

        if (window.confirm('确定要删除此会话吗？所有聊天历史和上传的文档都将被永久删除。')) {
            try {
                await apiClient.deleteSession();
                // 通知父组件
                if (typeof onSessionDeleted === 'function') {
                    onSessionDeleted();
                }
            } catch (error) {
                console.error('删除会话失败:', error);
                setError(error.message || '删除会话时发生错误');
            }
        }
    }, [sessionId, onSessionDeleted]);

    // 格式化时间
    const formatTime = useCallback((timestamp) => {
        const date = new Date(timestamp);
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }, []);

    // 处理错误关闭
    const handleCloseError = useCallback(() => {
        setError('');
    }, []);

    return (
        <div className="chat-window">
            <div className="chat-header">
                <div className="chat-title">
                    <h2>{sessionInfo?.agent_name || 'AI聊天助手'}</h2>
                    {sessionInfo && (
                        <div className="session-info">
                            <span className="model-info">
                                <FontAwesomeIcon icon={faRobot} className="mr-1" />
                                {sessionInfo.model_name}
                            </span>
                            <span className="doc-count">
                                <FontAwesomeIcon icon={fa-file} className="mr-1" />
                                {sessionInfo.document_count}个文档
                            </span>
                        </div>
                    )}
                </div>
                <div className="chat-actions">
                    <button 
                        className="btn btn-outline-primary mr-2" 
                        onClick={handleClearHistory}
                        disabled={isLoading || !sessionId}
                    >
                        <FontAwesomeIcon icon={faRefresh} /> 清除历史
                    </button>
                    <button 
                        className="btn btn-outline-danger" 
                        onClick={handleDeleteSession}
                        disabled={isLoading || !sessionId}
                    >
                        <FontAwesomeIcon icon={faTrash} /> 删除会话
                    </button>
                </div>
            </div>

            {error && (
                <div className="error-message">
                    <div className="alert alert-danger">
                        <FontAwesomeIcon icon={faExclamationTriangle} className="mr-2" />
                        {error}
                        <button 
                            type="button" 
                            className="close" 
                            onClick={handleCloseError}
                        >
                            <span>&times;</span>
                        </button>
                    </div>
                </div>
            )}

            <div className="chat-messages" ref={chatContainerRef}>
                {messages.map((message, index) => (
                    <div 
                        key={message.id} 
                        className={`message ${message.role} ${message.isStreaming ? 'streaming' : ''}`}
                    >
                        <div className="message-avatar">
                            {message.role === 'user' ? (
                                <FontAwesomeIcon icon={fa-user} />
                            ) : message.role === 'system' ? (
                                <FontAwesomeIcon icon={fa-info-circle} />
                            ) : (
                                <FontAwesomeIcon icon={fa-robot} />
                            )}
                        </div>
                        <div className="message-bubble">
                            <div className="message-content">
                                {message.role === 'system' ? (
                                    <div className="system-message">
                                        <span dangerouslySetInnerHTML={{ __html: message.content }} />
                                    </div>
                                ) : (
                                    <div className="markdown-content">
                                        <span dangerouslySetInnerHTML={{ __html: message.content }} />
                                    </div>
                                )}
                            </div>
                            <div className="message-meta">
                                <span className="timestamp">{formatTime(message.timestamp)}</span>
                            </div>
                        </div>
                    </div>
                ))}

                {isLoading && (
                    <div className="message assistant">
                        <div className="message-avatar">
                            <FontAwesomeIcon icon={fa-robot} />
                        </div>
                        <div className="message-bubble">
                            <div className="message-content">
                                <div className="typing-indicator">
                                    <span></span>
                                    <span></span>
                                    <span></span>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </div>

            <div className="chat-input">
                <div className="input-group">
                    <div className="custom-file">
                        <input 
                            type="file" 
                            className="custom-file-input" 
                            id="fileUpload" 
                            onChange={handleFileUpload}
                            disabled={isLoading || uploading}
                        />
                        <label className="custom-file-label" htmlFor="fileUpload">
                            <FontAwesomeIcon icon={faUpload} /> 上传文档
                        </label>
                    </div>
                    <textarea
                        ref={inputRef}
                        className="form-control"
                        placeholder="输入消息..."
                        value={inputValue}
                        onChange={(e) => setInputValue(e.target.value)}
                        rows={3}
                        disabled={isLoading || uploading}
                    ></textarea>
                    <div className="input-group-append">
                        <button
                            className="btn btn-primary send-button"
                            onClick={handleSendMessage}
                            disabled={!inputValue.trim() || isLoading || uploading}
                        >
                            {isLoading ? (
                                <FontAwesomeIcon icon={faSpinner} spin />
                            ) : (
                                <FontAwesomeIcon icon={faPaperPlane} />
                            )}
                        </button>
                    </div>
                </div>

                {uploading && (
                    <div className="upload-progress">
                        <div className="progress">
                            <div 
                                className="progress-bar progress-bar-striped progress-bar-animated" 
                                role="progressbar" 
                                style={{ width: `${uploadProgress}%` }} 
                                aria-valuenow={uploadProgress} 
                                aria-valuemin={0} 
                                aria-valuemax={100}
                            >
                                {uploadProgress}%
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default ChatWindow;
    